package com.xxx.client.android.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.ViewFlipper;

import com.xxx.client.android.R;
import com.xxx.client.android.adapter.ArticleAdapter;
import com.xxx.client.android.api.ArticleListEntry;
import com.xxx.client.android.api.ArticleVO;
import com.xxx.client.android.api.WSError;
import com.xxx.client.android.api.XXXApi;
import com.xxx.client.android.api.impl.XXXApiImpl;
import com.xxx.client.android.dialog.LoadingDialog;
import com.xxx.client.android.util.Tool;

/**
 * Allows content searching on Remote services
 */
public class SearchActivity extends Activity {

	enum SearchMode {
		titleName, author, articleContent
	};

	private Spinner mSearchSpinner;
	private ListView mSearchListView;
	private EditText mSearchEditText;
	private Button mSearchButton;
	private ViewFlipper mViewFlipper;

	private ArticleListEntry articleList;

	private SearchMode mSearchMode;
	private Integer submenuId;

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param c
	 *            context from which Activity should be started
	 * @param submenuId
	 *            submenuId, 0 for all submenuId
	 */
	public static void launch(Context c, Integer submenuId) {
		Intent intent = new Intent(c, SearchActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("submenuId", submenuId);
		intent.putExtras(bundle);
		c.startActivity(intent);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);

		if (savedInstanceState == null) {
			submenuId = getIntent().getExtras().getInt("submenuId");
		} else {
			submenuId = savedInstanceState.getInt("submenuId");
		}

		mSearchSpinner = (Spinner) findViewById(R.id.SearchSpinner);
		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
				R.array.search_modes, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSearchSpinner.setAdapter(adapter);

		mSearchButton = (Button) findViewById(R.id.SearchButton);
		mSearchButton.setOnClickListener(mSearchButtonListener);

		mSearchEditText = (EditText) findViewById(R.id.SearchEditText);
		mSearchListView = (ListView) findViewById(R.id.SearchListView);

		mViewFlipper = (ViewFlipper) findViewById(R.id.SearchViewFlipper);
		if (mSearchListView.getCount() == 0) {
			mViewFlipper.setDisplayedChild(2); // search list hint
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.about, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about_menu_item:
			Tool.about(this);
			break;
		default:
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// not support for search key
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// not support for search key
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		mSearchMode = (SearchMode) savedInstanceState.getSerializable("mode");
		if (mSearchMode != null) {
			ArticleAdapter adapter = new ArticleAdapter(this);
			adapter.setList((ArrayList<ArticleVO>) savedInstanceState
					.get("values"));
			mSearchListView.setAdapter(adapter);
			mSearchListView.setOnItemClickListener(mArticleClickListener);

			mViewFlipper.setDisplayedChild(savedInstanceState
					.getInt("flipper_page"));
			submenuId = savedInstanceState.getInt("submenuId", submenuId);
		}
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (mSearchMode != null) {
			ArticleAdapter adapter = (ArticleAdapter) mSearchListView
					.getAdapter();
			outState.putSerializable("values",
					(ArrayList<ArticleVO>) adapter.getList());

			outState.putInt("flipper_page", mViewFlipper.getDisplayedChild());
			outState.putInt("submenuId", submenuId);
		}
		super.onSaveInstanceState(outState);
	}

	private OnClickListener mSearchButtonListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String query = mSearchEditText.getText().toString();
			if (query.equals("")) {
				Tool.messageBox(SearchActivity.this,
						getString(R.string.search_list_hint));
			} else {
				new SearchingDialog(SearchActivity.this, R.string.searching,
						R.string.search_fail).execute(
						mSearchSpinner.getSelectedItemPosition(), submenuId);
			}
		}

	};

	private OnItemClickListener mArticleClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long time) {
			ArticleVO article = (ArticleVO) adapterView
					.getItemAtPosition(position);
			ArticleActivity.launch(SearchActivity.this,
					new Integer[] { article.getArticleId(), null, 1 });
		}
	};

	/**
	 * Allows cancelling search query
	 */
	private class SearchingDialog extends LoadingDialog<Integer, Integer> {

		private BaseAdapter mAdapter;

		public SearchingDialog(Activity activity, int loadingMsg, int failMsg) {
			super(activity, loadingMsg, failMsg);
		}

		@Override
		public Integer doInBackground(Integer... params) {
			articleSearch(params);
			return params[0];
		}

		@Override
		public void doStuffWithResult(Integer searchMode) {
			mSearchListView.setAdapter(mAdapter);

			if (mSearchListView.getCount() > 0) {
				mViewFlipper.setDisplayedChild(0); // display results
			} else {
				mViewFlipper.setDisplayedChild(1); // display no results message
			}

			mSearchListView.setOnItemClickListener(mArticleClickListener);
		}

		private void articleSearch(Integer[] params) {
			int id = params[0], submenuId = params[1];
			XXXApi service = new XXXApiImpl();
			String query = mSearchEditText.getText().toString();
			XXXApi.GetArticleNameListParam param = new XXXApi.GetArticleNameListParam();
			param.setKeyword(query);
			param.setSubmenuId(submenuId);
			try {
				switch (id) {
				case 0:
					param.setType(XXXApi.GetArticleNameListParam.KEYWORD_TYPE_1);
					break;
				case 1:
					param.setType(XXXApi.GetArticleNameListParam.KEYWORD_TYPE_2);
					break;
				case 3:
					param.setType(XXXApi.GetArticleNameListParam.KEYWORD_TYPE_3);
					break;

				default:
					return;
				}

				articleList = service.getArticleNameListByObject(param);

				ArticleAdapter articleAdapter = new ArticleAdapter(
						SearchActivity.this);
				articleAdapter.setList(articleList.getArticleList());
				articleAdapter.setListView(mSearchListView);
				mAdapter = articleAdapter;

			} catch (RuntimeException e) {
				e.printStackTrace();
			} catch (WSError e) {
				publishProgress(e);
				this.cancel(true);
			}
		}

	}

}
